/***********************************************************************
 maketiff.cpp - Glue between libtiff's TIFF writing code and an SDL
 	drawing surface.

 Created 2006.06.10 by Warren Young

 Copyright (c) 2006 by Pixel Corps.  This program may be used under
 the terms of the X11 license, a copy of which should have accompanied
 this program, in the LICENSE file.
***********************************************************************/

#include "maketiff.h"

#include <tiffio.h>
#include <SDL.h>

#include <iostream>

using namespace std;


//// SaveSurfaceAsTIFF /////////////////////////////////////////////////

bool
SaveSurfaceAsTIFF(SDL_Surface* pSurface, const char* pcFileName)
{
	// Open TIFF file for writing
	TIFF* tiff = TIFFOpen(pcFileName, "w");
	if (!tiff) {
		cerr << "Failed to create TIFF image file \"" << pcFileName <<
				"\"." << endl;
		return false;
	}

	// Set options on TIFF file
	TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, pSurface->w);
	TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, pSurface->h);
	TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 3);
	TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8);

	TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_NONE);

	TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
	
	TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, 1);
	TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

	TIFFSetField(tiff, TIFFTAG_XRESOLUTION, 72.0);
	TIFFSetField(tiff, TIFFTAG_YRESOLUTION, 72.0);
	TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);	

	// Write out scanlines
	for (int i = 0; i < pSurface->h; ++i) {
		char* row = (char*)pSurface->pixels + (i * pSurface->pitch);
		if (TIFFWriteScanline(tiff, row, i, 0) < 0) {
			cerr << "Failed to write scan line " << i <<
					" to TIFF file." << endl;
			return false;
		}
	}

	// We're done
	TIFFClose(tiff);
	return true;
}

